package recipe.renderer;

import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Recipe_rendererActivity extends Activity {
	public EditText textview;
	Behaviour behaviour;
	Recipe recipe;
	LinearLayout recipeSteps;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reciperenderer);

		textview = (EditText) findViewById(R.id.editText1);
		textview.setKeyListener(null);
		recipeSteps = (LinearLayout) findViewById(R.id.linearLayoutRecipeSteps);
		recipe = null;
		behaviour = null;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		int recipe_resource = getIntent().getIntExtra("recipe_resource", -1);
		if (recipe_resource == -1) {
			finish();
			return;
		}
		load_recipe(recipe_resource);
	}
	
	
	private void show_all() {
		if (behaviour == null)
			return;
		
		recipeSteps.removeAllViews();

	    Map<String, Long> eta_dict = behaviour.get_eta_dict(System.currentTimeMillis());
	        
	    //if last_show:
	    //    print "%s\n\n" % last_show
		long time_started_recipe = behaviour.time_started_recipe;
		double time_past = (System.currentTimeMillis() - time_started_recipe) /1000.0;
		TextView tv = new TextView(recipeSteps.getContext());
		tv.setText(String.format("%d ready, %d active, %d done, %d overdue, %.1f sec passed...", 
										recipe.find_available_tasks().size(),
										recipe.find_active_tasks().size(),
										recipe.find_done_tasks().size(),
										recipe.find_overdue_tasks().size(),
										time_past));
		recipeSteps.addView(tv);
		
	    //tasks = sorted(task_list, key= lambda t: (eta_dict[t.index], t.index))
		int index = 0;
	    for (Task t : recipe.tasks) {
	    	index++;
	    	CheckBox step = new CheckBox(recipeSteps.getContext());
	    	step.setClickable(false);
	        if (t.completed()) {
	        	step.setChecked(true);
	        	step.setText(String.format("%d) %s (from %.1f to %.1f)", 
	        									index, t.speech, 
	                                            (t.time_started - time_started_recipe)/1000.0, 
	                                            (t.time_finished - time_started_recipe)/1000.0));
	        }
	        else if (t.is_overdue()) {
	        	step.setText(String.format("%d) %s  (started %.1f, duration=%s)", 
	        									index, t.speech, 
                                                (t.time_started - time_started_recipe)/1000.0, 
                                                t.duration));
	        	step.setBackgroundColor(0xffddbb22);
	        }
	        else if (t.is_active()) {
	        	step.setText(String.format("%d) %s  (started %.1f, duration=%s)", 
	        									index, t.speech, 
                                                (t.time_started - time_started_recipe)/1000.0, 
                                                t.duration));
	        	step.setBackgroundColor(0xff22bbff);
	        }
	        else if (t.started()) {
	        	step.setText(String.format("%d) ERROR!!!  started but not active or completed!  [%s]", index, t.speech));
	        	step.setBackgroundColor(0xffff5555);
	        }
	        else {
	            String can_start =  t.can_start() ? ", CAN START!"  : "";
	            step.setText(String.format("%d) %s  (estimated will start in %.1f seconds, duration=%s%s)", 
            																		index, t.speech, 
            																		(eta_dict.get(t.id) - t.duration*1000 - time_started_recipe)/1000.0,
                                                                                    t.duration, 
	                                                                                can_start));
	            if (t.can_start())
	            	step.setBackgroundColor(0xff114466);
	        }
	        recipeSteps.addView(step);
	    }
	}
	             

	private void load_recipe(int resource) {
		textview.append("loading recipe...\n");
		recipe = new Recipe();
		recipe.parse_file(getResources().openRawResource(resource));
		textview.append("parsed " + Integer.toString(recipe.tasks.size()) + " tasks\n");
		textview.append("title= " + recipe.title + "\n");
		textview.append("source=" + recipe.source + "\n");
		show_all();		
	}

	public void load_func(View arg0) {
		load_recipe(R.raw.healthy_baked_chicken_nuggets);
	}

	public void run_func(View arg0) {
		if (recipe == null) {
			textview.append("no recipe is loaded...\n");
			return;
		}
		if ((behaviour != null) && (behaviour.is_running)) {
			textview.append("recipe already running...\n");
			return;
		}
		textview.append("running recipe...\n");
		if (behaviour == null)
			textview.append("Initiating behaviour...\n");
		behaviour = new Behaviour(this, recipe, this);
		behaviour.is_running = true;
		new Thread(new Runnable() {
			public void run() {
				behaviour.idle();
			}
		}).start();
	}

	public void stop_func(View arg0) {
		if ((behaviour == null) || (!behaviour.is_running)) {
			textview.append("recipe not running...\n");
			return;
		}
		textview.append("stopping execution...\n");
		behaviour.is_running = false;
	}

	public void done_func(View arg0) {
		if ((behaviour == null) || (!behaviour.is_running)) {
			textview.append("recipe not running...\n");
			return;
		}
		behaviour.done_func();
	}

	public void repeat_func(View arg0) {
		if ((behaviour == null) || (!behaviour.is_running)) {
			textview.append("recipe not running...\n");
			return;
		}
		behaviour.repeat_func();
	}

	public void say(final String str) {
		runOnUiThread(new Runnable() {
			public void run() {
				textview.append(str);
				show_all();
			}
		});
	}
}
